package com.example.understandvideo.controller;

import com.example.understandvideo.mapper.SettingDao;
import com.example.understandvideo.pojo.FileResult;
import com.example.understandvideo.pojo.ResultFul;
import com.example.understandvideo.service.CommonService;
import com.example.understandvideo.tool.FileUtils;
import com.example.understandvideo.tool.Tools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/api/gateway/common")
public class CommonController {
    @Autowired
    CommonService service;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultFul uploadFile(@RequestParam(value = "file", required = false) MultipartFile multipartFile) {
        if (Objects.isNull(multipartFile)) {
            return ResultFul.Error();
        }
        String uuid = Tools.getUUID();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        String nowDay = format.format(now);
        File file = new File(service.getWorkSpace() + File.separator + nowDay + File.separator + uuid + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")));
        try {
            // 确保父目录存在
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            multipartFile.transferTo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultFul.OK(file.getAbsolutePath());
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("path") String path,
                                                 @RequestParam(value = "filename", required = false) String filename) {
        try {
            // 1. 构建文件路径
            Path filePath = Paths.get(path);

            // 2. 检查文件是否存在
            if (!Files.exists(filePath)) {
                throw new FileNotFoundException("文件不存在: " + path);
            }

            // 3. 创建Resource对象
            Resource resource = new UrlResource(filePath.toUri());
            if(StringUtils.isBlank(filename)){
                filename = resource.getFilename();
            }
            // 4. 设置HTTP响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);

        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}
